//
//  AVViewController.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/10.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "AVViewController.h"
#import "SDCycleScrollView.h"
#import "SUNSlideSwitchView.h"
#import "SortModel.h"

#import "VideoListController.h"

#import "VideoDetailController.h"

#import "MyVideoRecord.h"

#import "HomeDetailViewController.h"

static NSString *INTERSTITIAL_STATE_TEXT = @"插屏状态";
@interface AVViewController ()<SUNSlideSwitchViewDelegate,GDTMobInterstitialDelegate>
{
    SUNSlideSwitchView *_slideView;
    NSMutableArray *_dataArr;
    
    VideoListController *_vc;
    NSInteger _currentIndex;
    
    SDCycleScrollView *_myscroll;
    NSArray *_myarr;
    BOOL _isError;
    
    GDTMobInterstitial *_interstitialObj;
}
@property(nonatomic, strong)NSMutableArray *controllers;
@end

@implementation AVViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startCollect) name:@"startcollect" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endCollect) name:@"endcollect" object:nil];
    
   // self.automaticallyAdjustsScrollViewInsets = NO;
    
    _dataArr = [NSMutableArray array];
    _controllers = [NSMutableArray array];
    [self initUI];
    [self getList];
    //[self showADview];
}

- (void)startCollect
{
    NSLog(@"----------------start");
    [self workBlock:_myscroll with:_myarr];
}

- (void)endCollect
{
    NSLog(@"----------------end");
    
    [self restBlock:_myscroll];
}

- (void)getList
{
    
    NSArray *titleArr = @[@"热门",@"电影",@"爆笑",@"综艺",@"科技",@"军事"];
    //列表key
    NSArray *idArr = @[@"hot",@"movie",@"recreat",@"variety",@"technology",@"military"];
    
    for (int i = 0; i < titleArr.count; i++) {
        SortModel *model = [[SortModel alloc]init];
        model.sortid = [idArr objectAtIndex:i];
        model.name = [titleArr objectAtIndex:i];
        [_dataArr addObject:model];
    }
    [self initControllers];
}

- (void)initControllers
{
//    VideoRecomendViewController *controller = [[VideoRecomendViewController alloc]init];
//    controller.title = @"推荐";
//    //进入详情
//    controller.passModel = ^(VideoListModel *model){
//        
//        VideoDetailController *controller = [[VideoDetailController alloc]init];
//        controller.model = model;
//        
//        [MyVideoRecord addOneRecord:model];
//        
//        [self.navigationController pushViewController:controller animated:YES];
//    };
//    //点击更多
//    controller.moreClick = ^(NSInteger i){
//        
//            UIButton *btn =  [_slideView.topScrollView viewWithTag:100 + i];
//        
//            [_slideView selectNameButton:btn];
//    };
//    //点击广告
//    controller.myad = ^(BannerModel *model){
//        
//        [MyAd collectClickAd:model];
//        
//        AdViewController *controller = [[AdViewController alloc]init];
//        if (![model.href hasPrefix:@"http://"]&&![model.href hasPrefix:@"https://"]) {
//            model.href = [NSString stringWithFormat:@"http://%@",model.href];
//        }
//        controller.urlstr = model.href;
//        [self.navigationController pushViewController:controller animated:YES];
//    };
//    //统计广告
//    controller.collectAd = ^(SDCycleScrollView *scroll,NSArray *arr,BOOL isError){
//        
//        _myscroll = scroll;
//        _myarr = arr;
//        _isError = isError;
//        [self workBlock:scroll with:arr];
//    };
//    //其他广告点击
//    controller.otheradclick = ^{
//        
//        HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
//        
//        detail.urlstr = @"http://u.ctrip.com/Union/CtripRedirect.aspx?TypeID=2&&AllianceID=301467&sid=771033&ouid=&app=0105A01&jumpUrl=http://hotels.ctrip.com/domestic/showhotellist.aspx?city=278";
//        [self.navigationController pushViewController:detail animated:YES];
//    };
//    
//    [_controllers addObject:controller];

    //广告位
    NSArray *adkeys = @[@"hot_video",@"movie_video",@"recreat_video",@"variety_video",@"technology_video",@"military_video"];
    
    for (int i=0; i<_dataArr.count; i++) {
        SortModel *model = _dataArr[i];
        
        VideoListController *controller = [[VideoListController alloc]init];
        controller.containedVC = self;
        controller.title = model.name;
        controller.model = model;
        controller.adkey = adkeys[i];
        //统计广告
        controller.collectAd = ^(SDCycleScrollView *scroll,NSArray *arr,BOOL isError){
            
            NSLog(@"接受");
            if (scroll) {
                _myscroll = scroll;
                _myarr = arr;
                _isError = isError;
                [self workBlock:scroll with:arr];
            }else{
                
                [self restBlock:_myscroll];
                _myscroll = nil;
            }
            
        };
        
        //点击广告
        controller.myad = ^(BannerModel *model){
            
            [MyAd collectClickAd:model];
            
            AdViewController *controller = [[AdViewController alloc]init];
            if (![model.href hasPrefix:@"http://"]&&![model.href hasPrefix:@"https://"]) {
                model.href = [NSString stringWithFormat:@"http://%@",model.href];
            }
            controller.urlstr = model.href;
            [self.navigationController pushViewController:controller animated:YES];
        };
        //其他广告点击
        controller.otheradclick = ^{
            
            HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
            
            detail.urlstr = @"http://u.ctrip.com/Union/CtripRedirect.aspx?TypeID=2&&AllianceID=301467&sid=771033&ouid=&app=0105A01&jumpUrl=http://hotels.ctrip.com/domestic/showhotellist.aspx?city=278";
            [self.navigationController pushViewController:detail animated:YES];
        };
        
        controller.passModel = ^(VideoListModel *videoModel){
            
            
            VideoDetailController *controller = [[VideoDetailController alloc]init];
            controller.model = videoModel;
            [MyVideoRecord addOneRecord:videoModel];
            
            [self.navigationController pushViewController:controller animated:YES];
            
            //[self showAD];
        };
        [_controllers addObject:controller];
    }
    
    
    
    [_slideView buildUI];
    
}
- (void)showADview
{
    _interstitialObj = [[GDTMobInterstitial alloc] initWithAppkey:GGTID placementId:@"7090619175285249"];
    
    _interstitialObj.delegate = self; //设置委托
    _interstitialObj.isGpsOn = NO; //【可选】设置GPS开关
    //预加载广告
    [_interstitialObj loadAd];
   
}
- (void)showAD
{
    if (_interstitialObj.isReady) {
        UIViewController *vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        [_interstitialObj presentFromRootViewController:vc];
    }
}

- (void)initUI
{
    CGRect rect = SCREEN;
    rect.origin.y += 20;
//    rect.size.height -= 8 + 64 + 40;
    _slideView = [[SUNSlideSwitchView alloc]initWithFrame:rect];
    _slideView.slideSwitchViewDelegate = self;
    
    __weak AVViewController *vc = self;

    _slideView.getIndex = ^(NSInteger i){
        
        ListViewController *list = vc.controllers[i];
        _myscroll = list.scrollView;
        [vc workBlock:list.scrollView with:list.adArr];
        
        _currentIndex = i;
        _vc = _controllers[i];
        [vc updateTable];
    };
    
    _slideView.tabItemNormalColor = [UIColor blackColor];
    [self.view addSubview:_slideView];
}

//- (void)shouldCollet
//{
//    if (_currentIndex == 0) {
//        
//        if (_myscroll&&_myarr) {
//            [self workBlock:_myscroll with:_myarr];
//        }
//    }else{
//        
//        [self restBlock:_myscroll];
//    }
//}

- (void)updateTable
{
    for (VideoListController *list in _controllers) {
        
        if ([list isKindOfClass:[VideoListController class]]) {
            list.table.scrollsToTop = NO;
        }
    }
    if ([_vc isKindOfClass:[VideoListController class]]) {
        _vc.table.scrollsToTop = YES;
    }
    
}

- (void)workBlock:(SDCycleScrollView *)view with:(NSArray *)arr
{
    [self restBlock:_vc.scrollView];
    if (self.tabBarController.selectedIndex != 3) {
        
        return;
    }
    if (!arr.count||!view) {
        
        return;
    }
    NSLog(@"开始统计");
    __weak NSArray *slide = arr;
    view.getContentOffset = ^(float offset){
        
        if (!_isError) {
            int i;
            
            if (offset == 0) {
                
                i = 0;
            }else{
                int index = offset/WIDTH;
                i = index%arr.count ;
            }
            
            NSLog(@"++++%d",i);
            if (i<slide.count) {
                BannerModel *model = slide[i];
                [MyAd collectShowAd:model];
            }
        
        }
    };
}

- (void)restBlock:(SDCycleScrollView *)view
{
    NSLog(@"不统计了》》》》》》》");
    if (view) {
        view.getContentOffset = ^(float offset){
            
            
        };
    }
    
}


- (NSUInteger)numberOfTab:(SUNSlideSwitchView *)view
{
    return _controllers.count;
}

- (UIViewController *)slideSwitchView:(SUNSlideSwitchView *)view viewOfTab:(NSUInteger)number
{
    return _controllers[number];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self restBlock:_myscroll];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_myscroll) {
        
        [self workBlock:_myscroll with:_myarr];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)interstitialSuccessToLoadAd:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Success Loaded.");
}

/**
 *  广告预加载失败回调
 *  详解:当接收服务器返回的广告数据失败后调用该函数
 */
- (void)interstitialFailToLoadAd:(GDTMobInterstitial *)interstitial error:(NSError *)error
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Fail Loaded." );
}

/**
 *  插屏广告将要展示回调
 *  详解: 插屏广告即将展示回调该函数
 */
- (void)interstitialWillPresentScreen:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Going to present.");
}

/**
 *  插屏广告视图展示成功回调
 *  详解: 插屏广告展示成功回调该函数
 */
- (void)interstitialDidPresentScreen:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Success Presented." );
}

/**
 *  插屏广告展示结束回调
 *  详解: 插屏广告展示结束回调该函数
 */
- (void)interstitialDidDismissScreen:(GDTMobInterstitial *)interstitial
{
    [_interstitialObj loadAd];
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Finish Presented.");
}

/**
 *  应用进入后台时回调
 *  详解: 当点击下载应用时会调用系统程序打开，应用切换到后台
 */
- (void)interstitialApplicationWillEnterBackground:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Application enter background.");
}

/**
 *  插屏广告曝光时回调
 *  详解: 插屏广告曝光时回调
 */
-(void)interstitialWillExposure:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Exposured");
}
/**
 *  插屏广告点击时回调
 *  详解: 插屏广告点击时回调
 */
-(void)interstitialClicked:(GDTMobInterstitial *)interstitial
{
    NSLog(@"%@:%@",INTERSTITIAL_STATE_TEXT,@"Clicked");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
